package com.jewelry.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.HMac;
import cn.hutool.crypto.digest.HmacAlgorithm;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jewelry.entity.User;
import com.jewelry.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping
    public Map<String, Object> userIsLogin(HttpSession session) {
        HashMap<String, Object> map = new HashMap<>();
        User user = (User) session.getAttribute("user");
        map.put("data", user);
        return map;
    }

    @DeleteMapping("delete/{id}")
    public Map<String, Object> delete(@PathVariable Integer id) {
        Map<String, Object> map = new HashMap<>();
        userService.removeById(id);
        map.put("message", "success");
        return map;
    }

    @PutMapping("update")
    public Map<String, Object> update(@RequestBody User user) {
        System.err.println("user = " + user);
        Map<String, Object> map = new HashMap<>();
        if(user.getRole() != 0){
            User user1 = userService.getById(user.getUserId());
            String salt = user1.getSalt();
            byte[] key = salt.getBytes();
            HMac hMac = new HMac(HmacAlgorithm.HmacMD5, key);
            // 使用MD5进行加密
            user.setPassword(hMac.digestHex(user.getPassword()));
        }
        userService.updateById(user);
        map.put("message", "success");
        return map;
    }

    @GetMapping("get/{pageNum}/{pageSize}")
    public Map<String, Object> get(@PathVariable Integer pageNum, @PathVariable Integer pageSize, HttpSession session) {
        Map<String, Object> map = new HashMap<>();
        map.put("message", userService.page(new Page<>(pageNum, pageSize), new LambdaQueryWrapper<User>().eq(User::getRole, 1)));
        return map;
    }

    @GetMapping("getUser/{id}")
    public Map<String, Object> get(@PathVariable Integer id, HttpSession session) {
        Map<String, Object> map = new HashMap<>();
        if (id != 0) {
            User user = userService.getById(id);
            map.put("message", user);
            map.put("role", 0);
        } else {
            User user = (User) session.getAttribute("user");
            map.put("message", user);
            map.put("role", user.getRole());
        }
        return map;
    }

    @PostMapping("login")
    public Map<String, Object> login(@RequestBody User user, HttpSession session) {
        System.out.println("user = " + user);
        Map<String, Object> map = new HashMap<>();
        if (userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getUserName, user.getUserName())) == null) {
            map.put("message", "user-not-existed");
            return map;
        }
        User user1 = userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getUserName, user.getUserName()));
        String salt = user1.getSalt();
        byte[] key = salt.getBytes();
        HMac hMac = new HMac(HmacAlgorithm.HmacMD5, key);
        // 使用MD5进行加密
        String spwd = hMac.digestHex(user.getPassword());
        if (user1.getPassword().equals(spwd)) {
            // 将用户信息添加到session中
//            redisTemplate.opsForValue().set("jewelry:user:"+user.getUserName(),user1, Duration.ofMinutes(10));
            session.setAttribute("user", user1);
            map.put("message", "success");
        } else {
            map.put("message", "pwd-error");
        }
        if (user.getUserName().equals("admin")) {
            User adminUser = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUserName, "admin"));
            if (adminUser.getPassword().equals(user.getPassword())) {
                session.setAttribute("user", adminUser);
                map.put("message", "admin-success");
                return map;
            }
        }
        return map;
    }

    @GetMapping("logout")
    public Map<String, Object> logout(HttpSession session) {
        Map<String, Object> map = new HashMap<>();
        // 从session中删除用户
        session.removeAttribute("user");
//        redisTemplate.delete("jewelry:user:"+username);
        map.put("message", "success");
        return map;
    }

    @PostMapping("regist")
    public Map<String, Object> regist(String username, String pw1) {
        Map<String, Object> map = new HashMap<>();
        if (userService.getOne(Wrappers.<User>query().eq("user_name", username)) != null) {
            map.put("message", "user-existed");
            return map;
        }
        User user = new User();
        user.setUserName(username);
        // 获取salt
        String salt = RandomUtil.randomString(5);
        byte[] key = salt.getBytes();
        HMac hMac = new HMac(HmacAlgorithm.HmacMD5, key);
        // 使用MD5进行加密
        String spwd = hMac.digestHex(pw1);
        user.setPassword(spwd);
        user.setRole(1);
        user.setSalt(salt);
        user.setCreateTime(new Date());
        userService.save(user);
        map.put("message", "success");
        return map;

    }

    @GetMapping("/user")
    public Map user(HttpSession session) {
        User user = (User) session.getAttribute("user");
        Map map = new HashMap();
        if (!ObjectUtil.isEmpty(user)) {
            map.put("message", "success");
            map.put("user", user);
        }
        return map;
    }


}
